import { getFeatureFunctions } from '@/api';
import { MciEmpty, MciSelect, MciSubCard, MciTable, MciTableColumn, MciButton, MciSvgIcon } from '@/components/base';
import { TableForm, Td, Tr } from '@/components/base/TableForm';
import { IOption } from '@/components/base/Select';
import { useFormMode } from '@/components/base/Form/mode';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useDictStore } from '@/store/dict';
import { TVariables } from '@/utils/graph';

export const FeatureConfig = defineComponent({
  name: 'FeatureConfig',
  setup() {
    const dictStore = useDictStore();
    // const value = ref<string>('');
    const options = ref<IOption[]>([]);
    // const currNodeVariablesReq = ref<TVariables[]>([]);
    // const currNodeVariablesRes = ref<TVariables[]>([]);
    const currentNode = useCurrentNode();
    // const loading = ref(false);
    const paramsMap = ref<any>({});

    const formMode = useFormMode();
    interface FeatureItem {
      value: string;
      currNodeVariablesReq: TVariables[];
      currNodeVariablesRes: TVariables[];
      options: IOption[];
    }
    interface FeatureValueItem {
      udfName: string;
    }

    const features = ref<FeatureItem[]>([]);
    const featureValues = ref<FeatureValueItem[]>([]);

    const buildFeatureItem = (): FeatureItem => {
      return {
        value: '',
        currNodeVariablesReq: [],
        currNodeVariablesRes: [],
        options: options.value.filter((item1) => !featureValues.value.some((item2) => item1.value === item2.udfName)) || []
      };
    };

    const buildOptions = () => {
      if (featureValues.value.length) {
        features.value = featureValues.value.map((item: any) => {
          return {
            value: item.udfName,
            currNodeVariablesReq: paramsMap.value[item.udfName]?.filter((item: any) => item.scope === 'REQUEST') || [],
            currNodeVariablesRes: paramsMap.value[item.udfName]?.filter((item: any) => item.scope === 'RESPONSE') || [],
            options:
              options.value.filter(
                (item1) => !featureValues.value.some((item2) => item2.udfName !== item.udfName && item1.value === item2.udfName)
              ) || []
          };
        });
      }
    };

    const save = () => {
      featureValues.value = features.value.map((item: any) => {
        return {
          udfName: item.value
        };
      });

      currentNode.saveFeatureData(featureValues.value || []);
      buildOptions();
    };

    const titleRight = () => {
      return (
        <div class="flex pr-12">
          {formMode?.mode === 'edit' && (
            <MciButton
              onClick={() => {
                features.value.push(buildFeatureItem());
              }}
              link>
              <MciSvgIcon width={18} height={18} name="plus" />
              <span class="text-value-14">特征函数</span>
            </MciButton>
          )}
        </div>
      );
    };

    const content = () => {
      return (
        <>
          {features.value.map((item, index) => {
            return (
              <div class="flex ">
                {true ? (
                  <div class="row-index-num text-gray-50 w-20 h-20 mr-8 mt-10 leading-[20px] text-center bg-green-600 rounded-[50%]">
                    {index + 1}
                  </div>
                ) : null}
                <div class="w-full">
                  <div>
                    <TableForm>
                      <Tr>
                        <Td span={24} class=" text-left bg-gray-100 py-12 pl-12">
                          特征函数
                        </Td>
                      </Tr>
                    </TableForm>
                  </div>
                  <MciSelect
                    class="w-full mt-8"
                    filterable
                    v-model={item.value}
                    list={item.options}
                    onChange={(val) => {
                      featureValues.value[index] = { udfName: val };
                      save();
                      getModelResponse(val, index);
                    }}
                  />
                  {item.currNodeVariablesReq.length > 0 && (
                    <div class="py-0">
                      {<div class="text-value-14 mt-12">特征入参</div>}
                      <MciTable data={item.currNodeVariablesReq}>
                        <MciTableColumn label="参数名称" prop="varName" />
                        <MciTableColumn label="字段Key" prop="varLabel" />
                        <MciTableColumn label="类型" prop="varType">
                          {(scope: any) => (
                            <>
                              <p>{dictStore.fieldTypeMap[scope.row.varType!]}</p>
                            </>
                          )}
                        </MciTableColumn>
                        <MciTableColumn label="默认值" prop="initValue" />
                      </MciTable>
                    </div>
                  )}
                  {item.currNodeVariablesRes.length > 0 && (
                    <div class="mb-20 py-8">
                      {<div class="text-value-14_bold">特征返回字段</div>}
                      <MciTable data={item.currNodeVariablesRes}>
                        <MciTableColumn label="字段名称" prop="varName" />
                        <MciTableColumn label="字段解释" prop="varLabel" />
                        <MciTableColumn label="类型" prop="varType">
                          {(scope: any) => (
                            <>
                              <p>{dictStore.fieldTypeMap[scope.row.varType!]}</p>
                            </>
                          )}
                        </MciTableColumn>
                      </MciTable>
                    </div>
                  )}
                  {item.currNodeVariablesReq.length <= 0 && item.currNodeVariablesRes.length <= 0 && (
                    <div class="custom-empty my-24">
                      <MciEmpty tipText={'暂无数据'} />
                    </div>
                  )}
                </div>
                {formMode?.mode === 'edit' && (
                  <MciButton
                    onClick={() => {
                      features.value.splice(index, 1);
                      save();
                    }}
                    icon={'mci-icon-delete'}
                    link={true}
                    type="danger"
                    plain={true}
                    class="row-index-remove-btn !h-32 cursor-pointer ml-30"
                  />
                )}
              </div>
            );
          })}
          {features.value.length <= 0 && (
            <div class="custom-empty my-24">
              <MciEmpty tipText={'暂无数据'} />
            </div>
          )}
        </>
      );
    };

    const getModelResponse = (id: string, index: number) => {
      // let variables: IGetModelGetRes['variables'] = [];
      // loading.value = true;
      // const res = await getModelGet({ id });
      // variables = res.variables || [];
      // loading.value = false;
      // currNodeVariablesReq.value = variables?.filter((item) => item.scope === 'REQUEST') || [];
      // currNodeVariablesRes.value = variables?.filter((item) => item.scope === 'RESPONSE') || [];
      // currentNode.saveCurrentPrivateNodeVariables(variables);

      const params = paramsMap.value[id] || [];

      if (features.value[index] && features.value[index].value === id) {
        features.value[index].currNodeVariablesReq = params?.filter((item: any) => item.scope === 'REQUEST') || [];
        features.value[index].currNodeVariablesRes = params?.filter((item: any) => item.scope === 'RESPONSE') || [];
        features.value[index].options =
          options.value.filter(
            (item1) => !featureValues.value.some((item2) => item2.udfName !== id && item1.value === item2.udfName)
          ) || [];
      }

      let allPrivateNodeVariables: any[] = [];

      features.value.forEach((item) => {
        if (item) {
          if (item.currNodeVariablesReq) {
            allPrivateNodeVariables = allPrivateNodeVariables.concat(item.currNodeVariablesReq);
          }
          if (item.currNodeVariablesRes) {
            allPrivateNodeVariables = allPrivateNodeVariables.concat(item.currNodeVariablesRes);
          }
        }
      });

      currentNode.saveCurrentPrivateNodeVariables(allPrivateNodeVariables);
    };

    onMounted(async () => {
      const data = currentNode.getNodeData();
      const res = await getFeatureFunctions({});

      const modelOptions =
        res?.map((item: any) => {
          paramsMap.value[item.key] = item.params || [];
          return {
            value: item.key,
            label: item.desc
          };
        }) || [];
      options.value = modelOptions;

      // if (data?.featureData && data.featureData.length && data.featureData[0]) {
      // value.value = data.featureData[0].udfName;
      // getModelResponse(data.featureData[0].udfName);
      // }
      featureValues.value = data?.featureData || [];
      buildOptions();
    });

    return () => {
      return (
        <MciSubCard title="节点设置">
          {{
            titleRight,
            default: content
          }}
        </MciSubCard>
      );
    };
  }
});
